<template>
  <div class="chat-container">
    <!-- 消息展示区域 -->
    <div class="message-area">
      <div
          v-for="(msg, index) in messages"
          :key="index"
          :class="['message', msg.role]"
      >
        <!-- 使用Markdown渲染容器 -->
        <div
            v-if="msg.role === 'assistant'"
            class="markdown-content"
            v-html="safeRenderMarkdown(msg.content)"
        ></div>
        <template v-else>
          {{ msg.content }}
        </template>
      </div>
      <div v-if="isLoading" class="loading">AI正在思考中...</div>
    </div>

    <!-- 输入控制区域 -->
    <div class="input-area">
      <input
          v-model="inputMessage"
          @keyup.enter="sendMessage"
          placeholder="输入你的问题..."
      />
      <button @click="sendMessage" :disabled="isLoading">
        {{ isLoading ? '生成中...' : '发送' }}
      </button>
    </div>
  </div>
</template>

<script setup>
import {getCurrentInstance, ref, onMounted} from 'vue';
import {marked} from 'marked';
import hljs from 'highlight.js';
import DOMPurify from 'dompurify';
import axios from 'axios';
import {generalScore} from "@/api/answer/answer.js";

const {proxy} = getCurrentInstance();
const inputMessage = ref('');
const messages = ref([]);
const isLoading = ref(false);
const paperId = ref(proxy.$route.query.paperId);
const recordId = ref(0);
const delFlag = ref('0');

// 配置marked
marked.setOptions({
  gfm: true,
  breaks: true,
  headerIds: true,
  highlight: (code, lang) => {
    return hljs.highlightAuto(code).value;
  },
  pedantic: false,
  sanitize: false,
});

// 安全渲染方法
const safeRenderMarkdown = (content) => {
  const rawHtml = marked(content);
  return DOMPurify.sanitize(rawHtml, {
    ALLOWED_TAGS: [
      'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
      'p', 'br', 'code', 'pre', 'strong', 'em',
      'a', 'ul', 'ol', 'li', 'blockquote', 'hr'
    ]
  });
};

// 发送消息
const sendMessage = async () => {
  const messageContent = inputMessage.value.trim();
  if (!messageContent || isLoading.value) return;

  try {
    messages.value.push({
      role: 'user',
      content: messageContent
    });

    messages.value.push({
      role: 'assistant',
      content: ''
    });
    const assistantIndex = messages.value.length - 1;

    isLoading.value = true;
    inputMessage.value = '';

    const response = await axios.get('http://47.111.128.196:8084/ai', {
      params: {userInput: messageContent}
    });

    if (response.data?.output?.choices?.[0]?.message?.content) {
      messages.value[assistantIndex].content =
          response.data.output.choices[0].message.content;
    } else {
      messages.value[assistantIndex].content = '未能获取有效回复';
    }

  } catch (error) {
    console.error('请求失败:', error);
    if (messages.value.length > 0) {
      messages.value[messages.value.length - 1].content = '请求失败，请重试';
    }
  } finally {
    isLoading.value = false;
  }
};

// 初始化测评分析
const initText = async () => {
  recordId.value = proxy.$route.query.recordId;
  paperId.value = proxy.$route.query.paperId;
  delFlag.value = proxy.$route.query.delFlag;

  if (!recordId.value) return;

  try {
    const res = await generalScore(paperId.value, delFlag.value, recordId.value);
    const data = res.data;

    const getTimeComment = (milliseconds) => {
      const mins = Math.round(milliseconds / 60000);
      if (mins < 3) return '（测试完成较快，建议确认作答认真程度）';
      if (mins > 15) return '（测试耗时较长，可能存在较多思考过程）';
      return '（测试用时在正常范围内）';
    };

    const formatDuration = (milliseconds) => {
      const seconds = Math.floor(milliseconds / 1000);
      const hours = Math.floor(seconds / 3600).toString().padStart(2, '0');
      const minutes = Math.floor((seconds % 3600) / 60).toString().padStart(2, '0');
      const remainingSeconds = (seconds % 60).toString().padStart(2, '0');
      return `${hours}时${minutes}分${remainingSeconds}秒`;
    };

    const totalTime = formatDuration(data.totalTime);
    const totalScore = data.totalScore;
    const factors = data.symptomClusterDTOList
        .map(item => `${item.name}：${item.score}`)
        .join('\n');

    const analysisText = `作为一名心理咨询分析师，我注意到用户完成了《${data.paperTitle}》心理测评。
      测评耗时：${totalTime}${getTimeComment(data.totalTime)}
      粗分（总分）：${totalScore}
      各维度因子分情况：${factors}
      根据本次测评结果进行专业的分析`;

    // 自动发送初始化消息
    await sendInitialMessage(analysisText);

  } catch (error) {
    console.error('初始化失败:', error);
  }
};

// 独立初始化消息发送方法
const sendInitialMessage = async (content) => {
  try {
    messages.value.push({
      role: 'user',
      content: content
    });

    messages.value.push({
      role: 'assistant',
      content: ''
    });
    const assistantIndex = messages.value.length - 1;

    const response = await axios.get('http://47.111.128.196:8084/ai', {
      params: {userInput: content}
    });

    if (response.data?.output?.choices?.[0]?.message?.content) {
      messages.value[assistantIndex].content =
          response.data.output.choices[0].message.content;
    } else {
      messages.value[assistantIndex].content = '分析结果生成失败';
    }

  } catch (error) {
    console.error('初始化请求失败:', error);
    // 确保 assistantIndex 存在才更新内容
    if (assistantIndex < messages.value.length) {
      messages.value[assistantIndex].content = '初始化分析请求失败';
    } else {
      // 如果 assistantIndex 超出范围，说明消息数组已被重置或清空
      messages.value.push({ role: 'assistant', content: '初始化分析请求失败' });
    }
  }
};

onMounted(() => {
  initText();
});
</script>

<style scoped>
.chat-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 30px;
  background: #f8f9fa;
  height: 85vh;
  display: flex;
  flex-direction: column;
}

.message-area {
  flex: 1;
  width: 100%;
  padding: 25px;
  background: white;
  border: 1px solid #e0e0e0;
  border-radius: 12px;
  margin-bottom: 25px;
  overflow-y: auto;
  box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.02);
}

.message-area::-webkit-scrollbar {
  width: 8px;
}

.message-area::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

.message-area::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 4px;
}

.message-area::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

.message {
  margin: 15px 0;
  padding: 18px 25px;
  border-radius: 20px;
  max-width: 90%;
  transition: transform 0.2s ease;
  word-break: break-word;
}

.user {
  background: linear-gradient(135deg, #6C8BFA, #7DA3FF);
  color: white;
  margin-left: auto;
  border-radius: 20px 20px 5px 20px;
  max-width: 85%;
}

.assistant {
  background: linear-gradient(145deg, #ffffff, #f9f9f9);
  margin-right: auto;
  border: 1px solid #eee;
  border-radius: 20px 20px 20px 5px;
  box-shadow: 2px 2px 8px rgba(0, 0, 0, 0.03);
  max-width: 90%;
}

.input-area {
  display: flex;
  gap: 15px;
  padding: 15px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  width: 100%;
}

input {
  flex: 1;
  padding: 16px 24px;
  border: 2px solid #e0e0e0;
  border-radius: 10px;
  font-size: 16px;
  transition: all 0.3s ease;
}

input:focus {
  border-color: #6C8BFA;
  box-shadow: 0 0 0 3px rgba(108, 139, 250, 0.1);
  outline: none;
}

button {
  padding: 12px 28px;
  background: linear-gradient(135deg, #6C8BFA, #5B7CDA);
  color: white;
  border: none;
  border-radius: 8px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
}

button:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(108, 139, 250, 0.3);
}

.markdown-content {
  line-height: 1.8;
  font-size: 16px;
  color: #333;
}

.markdown-content pre {
  background: #f9f9f9;
  padding: 1.2em;
  border-radius: 10px;
  border: 1px solid #e8e8e8;
}

.markdown-content code {
  font-family: 'JetBrains Mono', monospace;
  font-size: 14px;
  color: #2c3e50;
}

.markdown-content blockquote {
  border-left: 4px solid #6C8BFA;
  background: #f8f9ff;
  color: #444;
  padding: 1em;
  margin: 1.5em 0;
}

.loading {
  display: flex;
  align-items: center;
  justify-content: center;
  color: #666;
  font-size: 16px;
  gap: 10px;
}

.loading::after {
  content: "";
  width: 20px;
  height: 20px;
  border: 3px solid #ddd;
  border-top-color: #6C8BFA;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

body {
  overflow: hidden;
}
</style>
